package com.xinruke.hostels.dailymanage.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.xinruke.hostels.cache.extract.extractor.ReservationCacheExtractor;
import com.xinruke.hostels.central.manage.interfaces.api.CentralManageAPI;
import com.xinruke.hostels.common.cache.util.SysCodeUtil;
import com.xinruke.hostels.common.cache.util.SysSqlParamUtil;
import com.xinruke.hostels.common.constants.SysDicConstant;
import com.xinruke.hostels.common.exception.ArgumentException;
import com.xinruke.hostels.common.mybatis.MyExample;
import com.xinruke.hostels.common.po.MhHuiyuan;
import com.xinruke.hostels.common.po.XtMinganci;
import com.xinruke.hostels.common.po.YwJiudianPinglun;
import com.xinruke.hostels.common.util.EmptyUtil;
import com.xinruke.hostels.common.vo.ResultVO;
import com.xinruke.hostels.common.vo.query.EConditionOperator;
import com.xinruke.hostels.common.vo.query.QueryConditions;
import com.xinruke.hostels.common.vo.query.RowsDataVO;
import com.xinruke.hostels.dailymanage.interfaces.dto.*;
import com.xinruke.hostels.dailymanage.interfaces.enums.ECommentScoreDescribe;
import com.xinruke.hostels.dailymanage.mapper.YwJiudianPinglunMapper;
import com.xinruke.hostels.dailymanage.service.CommentService;
import com.xinruke.hostels.reservation.user.interfaces.dto.UserInfoQueryResultDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.util.Sqls;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author GuoZheng
 * @ClassName CommentServiceImpl
 * @date：2019/6/21
 * @version: V1.0.0
 * @description：
 */
@Service
public class CommentServiceImpl implements CommentService {
    @Resource
    private YwJiudianPinglunMapper ywJiudianPinglunMapper;

    @Resource
    private CentralManageAPI centralManageAPI;

    @Resource
    private ReservationCacheExtractor reservationCacheExtractor;

    Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public RowsDataVO<CommentInfoQueryResultDTO> list(CommentInfoQueryDto commentInfoQueryDto) {


        RowsDataVO<CommentInfoQueryResultDTO> dataVO = new RowsDataVO();
        QueryConditions conditions = new QueryConditions();

        conditions.addCondition("huiyuanId", EConditionOperator.EQULS, commentInfoQueryDto.getHuiyuanId());
        conditions.addCondition("jiudianId", EConditionOperator.EQULS, commentInfoQueryDto.getJiudianId());
        conditions.addCondition("leixing", EConditionOperator.EQULS, commentInfoQueryDto.getLeixing());
        conditions.addCondition("zhuangtai", EConditionOperator.EQULS, SysDicConstant.PINGLUNSHENHEZHUANGTAI_TONG_GUO);
        conditions.addCondition("shanchubiaoshi", EConditionOperator.EQULS, YwJiudianPinglun.SHANCHUBIAOSHI_WU_XIOA);

        MyExample example = new MyExample(YwJiudianPinglun.class, conditions, commentInfoQueryDto.getOrderFields());
        Page<CommentInfoQueryResultDTO> page = PageHelper.startPage(commentInfoQueryDto.getPageNo(), commentInfoQueryDto.getPageSize());
        List<YwJiudianPinglun> xtYewuyonghus = ywJiudianPinglunMapper.selectByExample(example);

        List<CommentInfoQueryResultDTO> noticeQueryResultDTOList = xtYewuyonghus.stream().map(n -> {
            CommentInfoQueryResultDTO dto = new CommentInfoQueryResultDTO();
            BeanUtils.copyProperties(n, dto);
            dto.setZhuangtaiMingcheng(SysCodeUtil.getSysParamDesc(SysDicConstant.PINGLUNSHENHEZHUANGTAI.toUpperCase(), String.valueOf(dto.getZhuangtai())));

            String huiyuanMingcheng = "";
            UserInfoQueryResultDTO userInfoQueryResultDTO = reservationCacheExtractor.getReservationUserInfo(dto.getHuiyuanId());
            String xingming = userInfoQueryResultDTO.getXingming();
            byte xingbie = userInfoQueryResultDTO.getXingbie();
            if (xingbie == MhHuiyuan.XINGBIE_NAN) {
                huiyuanMingcheng = xingming.substring(0, 1) + "先生";
            } else if (xingbie == MhHuiyuan.XINGBIE_NV) {
                huiyuanMingcheng = xingming.substring(0, 1) + "女士";
            }
            dto.setHuiyuanMingcheng(huiyuanMingcheng);
            dto.setJiudianMingcheng(SysSqlParamUtil.getSysParamDesc("jiudian.mingcheng".toUpperCase(), dto.getJiudianId()));

            dto.setFangjianpingjia(sensitiveWordCheck(dto.getFangjianpingjia()));
            dto.setFuwupingjia(sensitiveWordCheck(dto.getFuwupingjia()));
            return dto;
        }).collect(Collectors.toList());

        dataVO.setPageNo(page.getPageNum());
        dataVO.setTotalRecords(page.getTotal());
        dataVO.setTotalPages(page.getPages());
        dataVO.setRows(noticeQueryResultDTOList);
        return dataVO;
    }

    /**
     * 敏感词替换
     *
     * @param source
     * @return
     * @Author: ChenXiangpeng
     * @Date: 2019/7/30 18:14
     */
    private String sensitiveWordCheck(String source) {
        List<XtMinganci> list = SysSqlParamUtil.getSysParams("MINGANCI.ALL", XtMinganci.class);
        if (null == list || list.size() == 0) {
            return source;
        }
        for (XtMinganci dto : list) {
            if (source.contains(dto.getGuanjianci())) {
                source = source.replace(dto.getGuanjianci(), dto.getTihuanneirong());
            }
        }

        /*SensitiveWordCheckResultDTO result = new SensitiveWordCheckResultDTO();
        result.setLeirong(content);

        SensitiveWordCheckDTO sensitiveWordCheckDTO = new SensitiveWordCheckDTO();
        sensitiveWordCheckDTO.setLeirong(source);
        sensitiveWordCheckDTO.setPingbijibie(SysDicConstant.MINGANCIPINGBIJIBIE_YIBAN_PINGBI);
        sensitiveWordCheckDTO.setSuoshuxitong(SysDicConstant.MINGANCISUOSHUXITONG_ZHONG_YANG_JIAN_GUAN);
        ResultVO<SensitiveWordCheckResultDTO> check = centralManageAPI.check(sensitiveWordCheckDTO);*/
        return source;
    }

    @Override
    @Transactional
    public ResultVO<String> submit(CommentSubmitInfoDto params) {
        ResultVO<String> resultVO = ResultVO.fail();

        YwJiudianPinglun ywJiudianPinglun = new YwJiudianPinglun();
        BeanUtils.copyProperties(params, ywJiudianPinglun);
        ywJiudianPinglun.setChuangjianshijian(new Date());
        ywJiudianPinglun.setShanchubiaoshi(YwJiudianPinglun.SHANCHUBIAOSHI_WU_XIOA);
        ywJiudianPinglun.setGengxinshijian(new Date());
        ywJiudianPinglun.setZhuangtai(YwJiudianPinglun.ZHUANGTAI_DAISHENHE);
        int insert = ywJiudianPinglunMapper.insert(ywJiudianPinglun);
        if (insert > 0) {
            return ResultVO.success();
        }
        return resultVO;
    }

    @Override
    public ResultVO<CommentDetailQueryResultDTO> detail(CommentDetailQueryDTO params) {
        ResultVO<CommentDetailQueryResultDTO> resultVO = ResultVO.fail();

        CommentDetailQueryResultDTO dataDto = new CommentDetailQueryResultDTO();
        Sqls custom = Sqls.custom();
        //通过订单号查询
        if (!StringUtils.isEmpty(params.getDuiyingdingdanhao())) {
            custom.andEqualTo("duiyingdingdanhao", params.getDuiyingdingdanhao());
        }
        //通过id查询
        if (params.getId() != null) {
            custom.andEqualTo("id", params.getId());
        }
        List<YwJiudianPinglun> ywJiudianPingluns = ywJiudianPinglunMapper.selectByExample(Example.builder(YwJiudianPinglun.class)
                .where(custom
                        .andEqualTo("shanchubiaoshi", YwJiudianPinglun.SHANCHUBIAOSHI_WU_XIOA)
                ).build());
        if (CollectionUtils.isEmpty(ywJiudianPingluns)) {
            throw new ArgumentException("该评论不存在");
        }
        if (ywJiudianPingluns.get(0).getZhuangtai() != 1) {
            return ResultVO.fail("评论未审核或审核不通过");
        }
        BeanUtils.copyProperties(ywJiudianPingluns.get(0), dataDto);
        //获取入住时间

        //屏蔽敏感词
        dataDto.setFangjianpingjia(sensitiveWordCheck(dataDto.getFangjianpingjia()));
        dataDto.setFuwupingjia(sensitiveWordCheck(dataDto.getFuwupingjia()));

        dataDto.setZhuangtaiMingcheng(SysCodeUtil.getSysParamDesc(SysDicConstant.PINGLUNSHENHEZHUANGTAI.toUpperCase(), String.valueOf(dataDto.getZhuangtai())));

        UserInfoQueryResultDTO userDetail = reservationCacheExtractor.getReservationUserInfo(dataDto.getHuiyuanId());
        dataDto.setHuiyuanMingcheng(userDetail.getXingming());
        dataDto.setHuiyuanDianhua(userDetail.getShoujihao());
        dataDto.setJiudianMingcheng(SysSqlParamUtil.getSysParamDesc("jiudian.mingcheng".toUpperCase(), dataDto.getJiudianId()));

        resultVO.setCode(ResultVO.SUCCESS);
        resultVO.setMessage("操作成功");
        resultVO.setData(dataDto);


        return resultVO;
    }

    @Override
    @Transactional
    public ResultVO<String> del(CommentDelQueryDTO params) {
        ResultVO<String> resultVO = ResultVO.fail();
        YwJiudianPinglun ywJiudianPinglun = new YwJiudianPinglun();
        ywJiudianPinglun.setId(params.getId());
        ywJiudianPinglun.setGengxinshijian(new Date());
        ywJiudianPinglun.setShanchubiaoshi(YwJiudianPinglun.SHANCHUBIAOSHI_YOU_XIAO);
        int i = ywJiudianPinglunMapper.updateByPrimaryKeySelective(ywJiudianPinglun);

        if (i > 0) {
            resultVO.setCode(ResultVO.SUCCESS);
            resultVO.setMessage("删除成功");
        }

        return resultVO;
    }

    @Override
    @Transactional
    public ResultVO<String> audit(CommentAuditQueryDTO params) {

        ResultVO<String> resultVO = ResultVO.fail();
        //校验是否可以审批
        checkIsCanAudit(params.getId(), resultVO);
        if (resultVO.getCode() == ResultVO.FAIL) {
            return resultVO;
        }

        YwJiudianPinglun ywJiudianPinglun = new YwJiudianPinglun();
        ywJiudianPinglun.setId(params.getId());
        ywJiudianPinglun.setZhuangtai(params.getZhuangtai());
        ywJiudianPinglun.setGengxinshijian(new Date());
        int i = ywJiudianPinglunMapper.updateByPrimaryKeySelective(ywJiudianPinglun);

        if (i > 0) {
            resultVO.setCode(ResultVO.SUCCESS);
            resultVO.setMessage("操作成功");
        }

        return resultVO;

    }

    @Override
    @Transactional
    public ResultVO<String> modify(CommentModifyQueryDTO params) {

        ResultVO<String> resultVO = ResultVO.fail();
        //检验是否可以修改
        checkIsCanModify(params.getId(), resultVO);
        if (resultVO.getCode() == ResultVO.FAIL) {
            return resultVO;
        }

        YwJiudianPinglun ywJiudianPinglun = new YwJiudianPinglun();
        BeanUtils.copyProperties(params, ywJiudianPinglun);
        ywJiudianPinglun.setGengxinshijian(new Date());

        int i = ywJiudianPinglunMapper.updateByPrimaryKeySelective(ywJiudianPinglun);
        if (i > 0) {
            resultVO.setCode(ResultVO.SUCCESS);
            resultVO.setMessage("操作成功");
        }

        return resultVO;

    }

    @Override
    public CommentAverageResultDto average(Integer jiudianId) {
        CommentAverageResultDto resultDto = new CommentAverageResultDto();
        resultDto.setScore(ywJiudianPinglunMapper.selectAverageScore(jiudianId));
        resultDto.setDescribe(ECommentScoreDescribe.getDescribeByScore(resultDto.getScore()));

        return resultDto;
    }


    private void checkIsCanModify(Integer id, ResultVO<String> resultVO) {
        resultVO.setCode(ResultVO.SUCCESS);
        resultVO.setMessage("操作成功");
        YwJiudianPinglun ywJiudianPinglun = ywJiudianPinglunMapper.selectByPrimaryKey(id);
        if (ywJiudianPinglun.getZhuangtai().equals(YwJiudianPinglun.ZHUANGTAI_SHENHETONGUGO)) {
            resultVO.setCode(ResultVO.FAIL);
            resultVO.setMessage("该订单已被审核通过，不能修改");
        }
        resultVO.setCode(ResultVO.SUCCESS);
        resultVO.setMessage("操作成功");
    }

    private void checkIsCanAudit(Integer id, ResultVO<String> resultVO) {
        resultVO.setCode(ResultVO.SUCCESS);
        resultVO.setMessage("操作成功");
        YwJiudianPinglun ywJiudianPinglun = ywJiudianPinglunMapper.selectByPrimaryKey(id);
        if (!ywJiudianPinglun.getZhuangtai().equals(YwJiudianPinglun.ZHUANGTAI_DAISHENHE)) {
            resultVO.setCode(ResultVO.FAIL);
            resultVO.setMessage("该订单已被审核，不能再次审核");
        }

    }

    @Override
    public ResultVO<RowsDataVO<CommentInfoQueryResultDTO>> allComment(CommentAllInfoQueryDTO commentAllInfoQueryDTO) {
        logger.info("日常管理服务Service---根据条件获取结果的参数:{}", commentAllInfoQueryDTO);

        Page<CommentInfoQueryResultDTO> page = PageHelper.startPage(commentAllInfoQueryDTO.getPageNo(), commentAllInfoQueryDTO.getPageSize());
        List<CommentInfoQueryResultDTO> commentList = ywJiudianPinglunMapper.selectAllComment(commentAllInfoQueryDTO).stream().map(e -> {
            CommentInfoQueryResultDTO dto = new CommentInfoQueryResultDTO();
            BeanUtils.copyProperties(e, dto);
            dto.setZhuangtaiMingcheng(SysCodeUtil.getSysParamDesc(SysDicConstant.PINGLUNSHENHEZHUANGTAI.toUpperCase(), String.valueOf(dto.getZhuangtai())));

            dto.setHuiyuanMingcheng(reservationCacheExtractor.getReservationUserNameById(dto.getHuiyuanId()));
            dto.setJiudianMingcheng(SysSqlParamUtil.getSysParamDesc("jiudian.mingcheng".toUpperCase(), dto.getJiudianId()));
            return dto;
        }).collect(Collectors.toList());

        RowsDataVO<CommentInfoQueryResultDTO> rowsDataVO = new RowsDataVO<>();
        rowsDataVO.setPageNo(page.getPageNum());
        rowsDataVO.setTotalRecords(page.getTotal());
        rowsDataVO.setTotalPages(page.getPages());
        rowsDataVO.setRows(commentList);
        ResultVO<RowsDataVO<CommentInfoQueryResultDTO>> resultVO = ResultVO.success();
        resultVO.setData(rowsDataVO);
        System.out.println(resultVO);
        return resultVO;
    }


    @Override
    public ResultVO<CommentDetailQueryResultDTO> detailById(CommentDetailQueryDTO params) {
        ResultVO<CommentDetailQueryResultDTO> resultVO = ResultVO.fail();

        CommentDetailQueryResultDTO dataDto = new CommentDetailQueryResultDTO();
        Sqls custom = Sqls.custom();
        //通过id查询
        custom.andEqualTo("id", params.getId());
        List<YwJiudianPinglun> ywJiudianPingluns = ywJiudianPinglunMapper.selectByExample(Example.builder(YwJiudianPinglun.class)
                .where(custom
                        .andEqualTo("shanchubiaoshi", YwJiudianPinglun.SHANCHUBIAOSHI_WU_XIOA)
                ).build());
        if (CollectionUtils.isEmpty(ywJiudianPingluns)) {
            throw new ArgumentException("该评论不存在");
        }

        BeanUtils.copyProperties(ywJiudianPingluns.get(0), dataDto);
        //获取入住时间

        dataDto.setZhuangtaiMingcheng(SysCodeUtil.getSysParamDesc(SysDicConstant.PINGLUNSHENHEZHUANGTAI.toUpperCase(), String.valueOf(dataDto.getZhuangtai())));

        UserInfoQueryResultDTO userDetail = reservationCacheExtractor.getReservationUserInfo(dataDto.getHuiyuanId());

        if (EmptyUtil.isNotEmpty(userDetail)){
            dataDto.setHuiyuanMingcheng(userDetail.getXingming());
            dataDto.setHuiyuanDianhua(userDetail.getShoujihao());
        }
        dataDto.setJiudianMingcheng(SysSqlParamUtil.getSysParamDesc("jiudian.mingcheng".toUpperCase(), dataDto.getJiudianId()));
        resultVO.setCode(ResultVO.SUCCESS);
        resultVO.setMessage("操作成功");
        resultVO.setData(dataDto);
        return resultVO;
    }
}
